# coding=utf8

import requests
from bs4 import BeautifulSoup
import pprint

url = "https://theapplewiki.com/wiki/Models"

res = requests.get(url)

soup = BeautifulSoup(res.text, features='html.parser')

model_name = []
model = ''

for table in soup.find_all('table', attrs={'class': 'wikitable'}):
  ths = table.find_all('th')
  generation_index = 0
  indentifier_index = 0
  column_num = len(ths)
  for index,th in enumerate(ths):
    title = th.get_text()
    title = title.strip()
    if title == 'Generation':
      generation_index = index
    elif title == 'Identifier':
      indentifier_index = index
  
  trs = table.find_all('tr')
  for tr in trs:
    tds = tr.find_all('td')
    if len(tds) < column_num - 2:
      continue

    if len(tds) == column_num:
      model = tds[generation_index].get_text().strip()

      if 'iPod' in model or 'iPad' in model or 'iPhone' in model:
        for item in tds[indentifier_index].contents:
          item = item.get_text().strip()
          if '<br/>' in item or item is None or len(item) == 0:
            continue
          
          if not item == 'Unknown':
            for m in model_name:
              if item == m[0]:
                break
            else:
              model_name.append([item , model])

    else:
      if 'iPod' in model or 'iPad' in model or 'iPhone' in model:
        for item in tds[indentifier_index - column_num + len(tds)].contents:
          item = item.get_text().strip()
          if '<br/>' in item or item is None or len(item) == 0:
            continue

          if not item == 'Unknown':
            for m in model_name:
              if item == m[0]:
                break
            else:
              model_name.append([item , model])

pprint.pprint(model_name)

template = ''
for pair in model_name:
  padding = (20 - len(pair[0]) - 1)*' '
  template += '        case "{}":{}return "{}"\n'.format(pair[0], padding, pair[1])

pprint.pprint(template)

with open('template.swift','r') as f, open('UIDevice+.swift','w') as ff:
  template_file = f.read()
  template_file = template_file.replace('__template__', template)
  pprint.pprint(template_file)
  ff.write(template_file)

with open('Readme.md.template','r') as f, open('UIDevice+.swift') as ff, open('Readme.md','w') as fff:
  template_file = f.read()
  uidevice_file = ff.read()
  template_file = template_file.replace('__template__', uidevice_file)
  pprint.pprint(template_file)
  fff.write(template_file)
